package day12.handler.simpleChannelHandler.request;

import day12.packet.request.QuitGroupRequestPacket;
import day12.packet.response.QuitGroupResponsePacket;
import day12.util.session.GroupSession;
import day12.util.session.Session;
import day12.util.session.SessionUtil;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;

import java.util.List;

/**
 * @author chenshijie
 * @date 2024/1/2 15:37
 */
@ChannelHandler.Sharable
public class QuitGroupRequestHandler extends SimpleChannelInboundHandler<QuitGroupRequestPacket> {

    public static final QuitGroupRequestHandler INSTANCE = new QuitGroupRequestHandler();

    protected QuitGroupRequestHandler() {

    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, QuitGroupRequestPacket quitGroupRequestPacket) throws Exception {
        // 1. 获得群标识并删除该用户
        int groupId = quitGroupRequestPacket.getGroupId();
        GroupSession groupSession = SessionUtil.getGroupSession(groupId);
        String userName = SessionUtil.getSession(ctx.channel()).getUserName();
        System.out.println("收到用户【" + userName + "】退出群号【" + groupId + "】的申请");
        ChannelGroup channelGroup = groupSession.getChannelGroup();
        channelGroup.remove(ctx.channel());
        groupSession.setChannelGroup(channelGroup);

        List<Session> userSessions = groupSession.getUserSessions();
        userSessions.remove(SessionUtil.getSession(ctx.channel()));
        groupSession.setUserSessions(userSessions);

        // 2. 当群人数为0时，删除该群
        if (channelGroup.size() == 0) {
            System.out.println("群号【" + groupId + "】没有人了，删除该群");
            SessionUtil.unBindGroupSession(groupId);
        }


        // 3. 构造退群响应发送给客户端
        QuitGroupResponsePacket quitGroupResponsePacket = new QuitGroupResponsePacket();
        quitGroupResponsePacket.setGroupId(groupId);
        quitGroupResponsePacket.setSuccess();

        ctx.channel().writeAndFlush(quitGroupResponsePacket);
    }
}
